package com.ja.openchat.ui.contact;

import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.FragmentContactDetailListBinding;
import com.ja.openchat.ui.chat.ChatActivity;
import com.ja.openchat.ui.chat.FileDisplayActivity;
import com.ja.openchat.ui.chat.MessageViewModel;
import com.ja.openchat.ui.chat.PreviewMediaActivity;
import com.ja.openchat.ui.chat.PreviewWebViewActivity;
import com.ja.openchat.ui.chat.audio.AudioPlayManager;
import com.ja.openchat.ui.chat.audio.IAudioPlayListener;
import com.ja.openchat.ui.chat.group.JsoupTaskCallback;
import com.ja.openchat.ui.chat.group.adapter.GroupSettingChildAdapter;
import com.ja.openchat.viewmodels.ContactDetailChildViewModel;
import com.ja.openchat.views.AppFileReaderView;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.contact.ChatsInfo;
import com.zy.openchat.core.model.file.DocumentInfo;
import com.zy.openchat.core.model.group.JsoupTaskEvent;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.MessageInfo;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseFragment;

public class ContactDetailChildFragment extends BaseFragment<FragmentContactDetailListBinding, ContactDetailChildViewModel> {

    private int pageIndex = 0;
    private ChatInfo conversation;
    private GroupSettingChildAdapter messageAdapter;
    private static final int MESSAGE_LOAD_AROUND = 50;
    private long focusMessageId = 0;
    private GroupCommonAdapter mGroupCommonAdapter;
    private long offset_chat_id = 0;
    private int LIMIT = 20;
    private List<ChatInfo> chatInfos;

    public static ContactDetailChildFragment newInstance(int position, ChatInfo chatInfo){
        ContactDetailChildFragment fragment = new ContactDetailChildFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable("chat",chatInfo);
        bundle.putInt("position",position);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_contact_detail_list;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    protected void initDataAndEvent() {
        if(getArguments()!=null){
            pageIndex = getArguments().getInt("position");
            conversation = getArguments().getParcelable("chat");
        }
        if(pageIndex<5){
            wrapperMessages();
        }else{
            wrapperGroup();
        }
    }


    @Override
    public void initView() {
        super.initView();
        initDataAndEvent();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    private void requestGroups(long offsetChatId){
        if(conversation==null){
            return;
        }
        TelegramManager.getTelegramManager().getGroupsInCommon(getContext(), conversation.userId(),offsetChatId,LIMIT, new TgResultBlock<ChatsInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, ChatsInfo chatsInfo) {
                if (chatsInfo!=null) {
                    List<Long> chatIds = chatsInfo.chat_ids;
                    if(chatIds != null && chatIds.size() > 0){
                        offset_chat_id = chatIds.get(chatIds.size()-1);
                        HashMap<Long, ChatInfo> hashMap = new HashMap<>();
                        for (long chatId : chatIds) {
                            TelegramManager.getTelegramManager().requestChatInfoByChatId(getContext(), chatId, new TgResultBlock<ChatInfo>() {
                                @Override
                                public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                                    hashMap.put(chatId,obj);
                                    reloadListUI(hashMap,offsetChatId);
                                }

                                @Override
                                public void onTimeout(Map<String, Object> request) {

                                }
                            });
                        }
                    }
                }else{
                    reloadListUI(null,offsetChatId);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    private void wrapperGroup(){
        chatInfos = new ArrayList<>();
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mGroupCommonAdapter = new GroupCommonAdapter(chatInfos);
        binding.recyclerView.setAdapter(mGroupCommonAdapter);
        mGroupCommonAdapter.setEmptyView(R.layout.status_center_empty_view_wrap);
        mGroupCommonAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                ChatActivity.startActivity(getActivity(),mGroupCommonAdapter.getItem(position));
            }
        });
        mGroupCommonAdapter.getLoadMoreModule().setEnableLoadMore(true);
        mGroupCommonAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                requestGroups(offset_chat_id);
            }
        });
        requestGroups(offset_chat_id);
    }

    private void reloadListUI(HashMap<Long,ChatInfo> hashMap,long offsetChatId){
        if(chatInfos==null){
            chatInfos = new ArrayList<>();
        }else{
            if(offsetChatId==0){
                chatInfos.clear();
            }
        }
        if(hashMap!=null&&hashMap.size()>0){
            for (Long o : hashMap.keySet()) {
                ChatInfo fullInfo = hashMap.get(o);
                if(fullInfo.isSuperGroup()){
                    chatInfos.add(fullInfo);
                }
            }
            if(hashMap.size()<LIMIT){
                mGroupCommonAdapter.getLoadMoreModule().loadMoreEnd();
            }else{
                mGroupCommonAdapter.getLoadMoreModule().loadMoreComplete();
            }
        }else{
            mGroupCommonAdapter.getLoadMoreModule().loadMoreEnd();
        }
        mGroupCommonAdapter.notifyDataSetChanged();
    }


    @Override
    protected boolean isHaveEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onJsoupEvent(JsoupTaskEvent event){
        if(pageIndex == 3&&event!=null&&!TextUtils.isEmpty(event.url)&&event.documentInfo!=null&&messageAdapter!=null&&messageAdapter.getData()!=null){
            List<MessageInfo> messageInfos = messageAdapter.getData();
            for(MessageInfo messageInfo: messageInfos){
                if(event.url.equals(JsoupTaskCallback.checkUrl(messageInfo.textTypeContent))){
                    messageInfo.setHtmlDocumentInfo(event.documentInfo);
                }
            }
            messageAdapter.notifyDataSetChanged();
        }
    }


    private void requestChatData(){
        TelegramManager.getTelegramManager().getChatMessageList(getContext(),conversation.id, focusMessageId, 0, MESSAGE_LOAD_AROUND, new TgResultBlock<List<MessageInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<MessageInfo> obj) {
                if(obj!=null&&obj.size()>0){
                    List<MessageInfo> messages = new ArrayList<>();
                    for(MessageInfo messageInfo:obj){
                        if(isMatch(messageInfo)){
                            messages.add(0,messageInfo);
                        }
                    }
                    focusMessageId = obj.get(0).id;
                    if(focusMessageId==0){
                        messageAdapter.setNewData(messages);
                    }else{
                        messageAdapter.addData(messages);
                    }
                    messageAdapter.getLoadMoreModule().loadMoreComplete();
                    if(messages.size()==0){
                        requestChatData();
                    }
                }else{
                    messageAdapter.getLoadMoreModule().loadMoreEnd();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                messageAdapter.getLoadMoreModule().loadMoreEnd();
            }
        });
    }

    private boolean isMatch(MessageInfo messageInfo){
        if(pageIndex ==0){
            return messageInfo.messageType == TelegramManager.MessageType.MessageType_Photo||messageInfo.messageType == TelegramManager.MessageType.MessageType_Video;
        }else if(pageIndex ==1){
            return messageInfo.messageType == TelegramManager.MessageType.MessageType_Document;
        }else if(pageIndex ==2){
            return messageInfo.messageType == TelegramManager.MessageType.MessageType_Audio;
        }else if(pageIndex ==3){
            return messageInfo.messageType == TelegramManager.MessageType.MessageType_Text && MessageViewModel.isLinkString(messageInfo.textTypeContent);
        }else{
            return messageInfo.messageType == TelegramManager.MessageType.MessageType_Animation;
        }
    }

    private void wrapperMessages(){
        binding.recyclerView.setLayoutManager(new GridLayoutManager(getContext(),3));
        messageAdapter = new GroupSettingChildAdapter();
        binding.recyclerView.setAdapter(messageAdapter);
        viewModel.setAdapter(conversation,messageAdapter);
        messageAdapter.setEmptyView(R.layout.status_center_empty_view_wrap);
        messageAdapter.getLoadMoreModule().setEnableLoadMore(true);
        messageAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                requestChatData();
            }
        });
        messageAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                MessageInfo messageInfo = messageAdapter.getItem(position);
                if(pageIndex == 0){
                    PreviewMediaActivity.previewMedia(getContext(),messageAdapter.getData(),position);
                }else if(pageIndex == 1){
                    if(messageInfo.content!=null&&messageInfo.content.document!=null){
                        DocumentInfo documentInfo = messageInfo.content.document;
                        if(!documentInfo.isFileDownloaded()){
                            ToastUtils.showShort(getString(R.string.file_downloading_text));
                            TelegramManager.getTelegramManager().downloadFile(messageInfo.chat_id+"_" + messageInfo.id, documentInfo.document.id, 0, TelegramManager.FileType.FileType_Message_Document);
                            return;
                        }
                        if(DocumentInfo.isImageFile(documentInfo.file_name)||DocumentInfo.isVideoFile(documentInfo.file_name)){
                            PreviewMediaActivity.previewImage(getContext(),messageInfo);
                        }else{
                            String fileExtension = AppFileReaderView.getFileType(documentInfo.file_name);
                            FileDisplayActivity.startActivity(getContext(),documentInfo.localFilePath(),fileExtension);
                        }
                    }
                }else if(pageIndex == 2){
                    if (!messageInfo.isAudioFileDownloaded()) {
                        TelegramManager.getTelegramManager().downloadFile(messageInfo.chat_id+"_" + messageInfo.id, messageInfo.getAudioFileId(), 0, TelegramManager.FileType.FileType_Message_Audio);
                        ToastUtils.showShort(getString(R.string.file_downloading_text));
                        return;
                    }
                    File file = new File(messageInfo.audioLocalPath());
                    playAudio(messageInfo,file);
                }else if(pageIndex == 3){
                    String link = messageInfo.textTypeContent;
                    PreviewWebViewActivity.loadUrl(getContext(), "", link);
                }else{
                    PreviewMediaActivity.previewMedia(getContext(),messageAdapter.getData(),position);
                }
            }
        });
        requestChatData();
    }

    private void playAudio(MessageInfo message, File file) {
        Uri uri = Uri.fromFile(file);
        AudioPlayManager.getInstance().startPlay(App.getInstanse(), uri, new IAudioPlayListener() {
            @Override
            public void onStart(Uri var1, int lengthoftime) {
                if (uri.equals(var1)) {
                }
            }

            @Override
            public void onStop(Uri var1) {
                if (uri.equals(var1)) {

                }
            }

            @Override
            public void onProgress(Uri var1,int  currentPosition,int secendProssed, int totalLenght) {

            }

            @Override
            public void onComplete(Uri var1) {
                if (uri.equals(var1)) {

                }
            }
        });
    }


}
